<?php

class LoginController extends Zend_Controller_Action
{
    public function init()
    {
		/* Initialize action controller here */
    }

    // added getForm() and took out $request because its not needed in here -andylt
    public function indexAction()
    {
		$this->view->form=$this->getForm();
    }
	
    public function getForm() 
    {
    	return new Application_Form_Login(array('action'=>'/login/process','method'=>'post'));
    }
    
    public function loginAction()
    {
    	$user = $_POST['username'];
		$password = md5($_POST['password']);
		$dbhost = 'localhost';
		$dbuser = 'root';
		$dbpass = 'Comp523!';

		$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (mysql_error());
		
		if (!$conn) {
			echo "Unable to connect to DB: " . mysql_error();
			exit;
		}
		
		$dbname = 'network_inventory';
		$db = mysql_select_db($dbname);
    	$qstring = "SELECT * FROM users";
		$result = mysql_query($qstring);
		
		mysql_close();
		
		while ($row = mysql_fetch_assoc($result)) {
			if ($user == $row['user'] && $password == $row['password']) {
				$match = true;
				$curruser = $user;
			}
		}

		if ($match == true)
			$this->view->message="<h1>SUCCESS! You are now logged in as " . $curruser . ".</h1>";
		else
       		$this->view->message='<h1>Failure! Either the username does not exist or the password is incorrect.</h1>';
    }
    
	public function preDispatch()
    {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            // If the user is logged in, we don't want to show the login form;
            // however, the logout action should still be available
            if ('logout' != $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index', 'index');
            }
        } else {
            // If they aren't, they can't logout, so that action should 
            // redirect to the login form
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index');
            }
        }
    }
    
	public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index'); // back to login page
    }
    
    function __call($action, $arguments)
    {
    }
}



